package com.jds.test.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AttributeKey;

import java.net.URLDecoder;

/**
 * Created by sunyuming on 18/9/3.
 */
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    public static AttributeKey<String> key = AttributeKey.valueOf("userName");

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        String url = request.getUri();

        if(-1 != url.indexOf("/ws")) {
            String temp [] = url.split(";");
            String name = URLDecoder.decode(temp[1], "UTF-8");
            ctx.channel().attr(key).set(name);

            // 在更高版本中4.1.17.Final，此句是需要的
        //    request.setUri("/ws");
            // 传递到下一个handler：升级握手
            ctx.fireChannelRead(request.retain());
        } else {
            System.out.println("not socket");
            ctx.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
